package com.woniu40.petai_user.web;

import com.woniu40.petai_user.entity.Address;
import com.woniu40.petai_user.entity.Order;
import com.woniu40.petai_user.entity.User;
import com.woniu40.petai_user.service.AddressService;
import com.woniu40.petai_user.service.OrderItemService;
import com.woniu40.petai_user.vo.AddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("orderItem")
public class OrderItemController {
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    AddressService addressService;

    @PostMapping("/add")
    public String add(AddressVo addressVo, HttpSession session){
        User user = (User) session.getAttribute("user");
        //保存用户输入的地址信息
        Address address = new Address(null,user.getUserId(),addressVo.getArea(),addressVo.getItemAddress(),addressVo.getReceiverPhone(),addressVo.getReceiverName(),addressVo.getReceiverEmail(),1);
        addressService.addAddress(address);
        //创建订单及订单明细
        List<Integer> idList = Arrays.stream(addressVo.getCartIds().split(","))
                .map(s -> Integer.valueOf(s))
                .collect(Collectors.toList());
        Order order = orderItemService.addOrderItem(idList, address.getAddressId(), user.getUserId());

        session.setAttribute("orderNum",order.getOrderNum());
        session.setAttribute("totalPrice",order.getTotalPrice());

        return "forward:/pay";
    }

}
